package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.dao.SysDictDataDAO;
import com.ruoyi.system.dao.SysDictTypeDAO;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;

/**
 * 字典 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysDictTypeServiceImpl implements ISysDictTypeService
{
    @Autowired
    private SysDictTypeDAO dictTypeDAO;

    @Autowired
    private SysDictDataDAO dictDataDAO;
    
    
    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     * 
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public Page<SysDictType> selectDictTypeList(SysDictType dictType,Pageable pageinfo)
    {
		return dictTypeDAO.findAll(getSpecification(dictType),pageinfo);
    }
    
	@Override
	public List<SysDictType> selectDictTypeList(SysDictType dictType) {
		return dictTypeDAO.findAll(getSpecification(dictType));
	}
	
	private Specification<SysDictType> getSpecification(SysDictType dictType){
		return (root, criteriaQuery, criteriaBuilder) -> {
			List<Predicate> predicateList = new ArrayList<>();
			if (!StringUtils.isEmpty(dictType.getDictName())) {
				predicateList.add(criteriaBuilder.like(root.get("dictName"), "%"+dictType.getDictName()+"%"));
			}
			if (!StringUtils.isEmpty(dictType.getStatus())) {
				predicateList.add(criteriaBuilder.like(root.get("status"), "%"+dictType.getStatus()+"%"));
			}
			if (!StringUtils.isEmpty(dictType.getDictType())) {
				predicateList.add(criteriaBuilder.equal(root.get("dictType"), dictType.getDictType()));
			}
			if (!StringUtils.isNull(dictType.getParams().get("beginTime"))) {
				predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("create_time"), dictType.getParams().get("beginTime").toString()));
			}
			
			if (!StringUtils.isNull(dictType.getParams().get("endTime"))) {
				predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("create_time"), dictType.getParams().get("endTime").toString()));
			}
			
			Predicate[] p = new Predicate[predicateList.size()];
			return criteriaBuilder.and(predicateList.toArray(p));
		};
	}

    /**
     * 根据所有字典类型
     * 
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll()
    {
        return dictTypeDAO.findAll();
    }

    /**
     * 根据字典类型查询字典数据
     * 
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType)
    {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = dictDataDAO.findByDictType(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    @Override
    public HashMap<String, ArrayList<SysDictData>> selectDictDataByTypes(String[] dictTypes) {
        List<SysDictData> dictdatas = dictDataDAO.findByDictTypeIn(dictTypes);
        if(StringUtils.isNull(dictdatas)){
            return null;
        }
        HashMap<String, ArrayList<SysDictData>> datas = new HashMap<String, ArrayList<SysDictData>>();
        dictdatas.forEach((dictdata)->{
            String key = StringUtils.toCamelCase(dictdata.getDictType());
            if(!datas.containsKey(key)){
                datas.put(key,new ArrayList<SysDictData>());
            }
            datas.get(key).add(dictdata);
        });
        return datas;
    }

    /**
     * 根据字典类型ID查询信息
     * 
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId)
    {
        return dictTypeDAO.findById(dictId).get();
    }

    /**
     * 根据字典类型查询信息
     * 
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType)
    {
        return dictTypeDAO.findByDictType(dictType);
    }

    /**
     * 批量删除字典类型信息
     * 
     * @param dictIds 需要删除的字典ID
     */
    @Transactional
    @Override
    public void deleteDictTypeByIds(Long[] dictIds)
    {
        for (Long dictId : dictIds)
        {
            SysDictType dictType = selectDictTypeById(dictId);
            
            
            Specification<SysDictData> specification = (root, criteriaQuery, criteriaBuilder) -> {
    			List<Predicate> predicateList = new ArrayList<>();
    			if (!StringUtils.isEmpty(dictType.getDictType())) {
    				predicateList.add(criteriaBuilder.equal(root.get("dictType"), dictType.getDictType()));
    			}
    			
    			Predicate[] p = new Predicate[predicateList.size()];
    			return criteriaBuilder.and(predicateList.toArray(p));
    		};
            
            if (dictDataDAO.count(specification) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dictTypeDAO.deleteById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache()
    {
        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");
        Map<String, List<SysDictData>> dictDataMap = sysDictDataService.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet())
        {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache()
    {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache()
    {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public SysDictType insertDictType(SysDictType dict)
    {
        dict = dictTypeDAO.save(dict);
        DictUtils.setDictCache(dict.getDictType(), null);
        return dict;
    }

    /**
     * 修改保存字典类型信息
     * 
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictType dict)
    {
        SysDictType oldDict = dictTypeDAO.findById(dict.getDictId()).get();
        dictDataDAO.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        dictTypeDAO.save(dict);
        List<SysDictData> dictDatas = dictDataDAO.findByDictType(dict.getDictType());
        DictUtils.setDictCache(dict.getDictType(), dictDatas);
        return 1;
    }

    /**
     * 校验字典类型称是否唯一
     * 
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict)
    {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = dictTypeDAO.findByDictType(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

}
